package com.dudy.common.util;

import org.apache.commons.lang3.StringUtils;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;
import java.util.UUID;

/**
 * @program: common
 * @author: dudy
 * @create: 2020-12-21 10:08
 * @description: 一些常用的工具类
 **/
public class CommonUtil {
    /**
     * 获取ip地址，如果没有外网ip，则返回内网ip
     *
     * @return
     * @throws Exception
     */
    public static String getLocalHost() {
        String localIP = null;
        Enumeration<NetworkInterface> networks = null;
        try {
            localIP = InetAddress.getLocalHost().getHostAddress();
            networks = NetworkInterface.getNetworkInterfaces();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (SocketException e) {
            e.printStackTrace();
        }
        InetAddress ip = null;
        Enumeration<InetAddress> addrs;
        while (networks.hasMoreElements()) {
            addrs = networks.nextElement().getInetAddresses();
            while (addrs.hasMoreElements()) {
                ip = addrs.nextElement();
                if (ip != null
                        && ip instanceof Inet4Address
                        && ip.isSiteLocalAddress()
                        && !ip.getHostAddress().equals(localIP)) {
                    return ip.getHostAddress();
                }
            }
        }
        // 如果没有外网IP，就返回内网IP
        return localIP;
    }

    public static String getStackTrace(Throwable throwable) {
        if (throwable == null) {
            return "";
        }
        StringWriter stringWriter = new StringWriter();
        try (
                PrintWriter printWriter = new PrintWriter(stringWriter)) {
            throwable.printStackTrace(printWriter);
            printWriter.flush();
            String s = stringWriter.toString();
            if (StringUtils.isNotBlank(s) && s.length() > 523) {
                s = s.substring(0, 523);
            }
            return s;
        }
    }

    public static String getUuid() {
        return UUID.randomUUID().toString().replace("-", "");
    }
}
